/*
 * Copyright 2017-2025 original authors
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * https://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package io.micronaut.inject.writer;

import io.micronaut.core.annotation.Internal;
import org.jspecify.annotations.NonNull;
import org.jspecify.annotations.Nullable;
import io.micronaut.inject.ast.ClassElement;
import io.micronaut.inject.visitor.VisitorContext;
import io.micronaut.sourcegen.bytecode.ByteCodeWriter;
import io.micronaut.sourcegen.model.ObjectDef;
import org.objectweb.asm.ClassWriter;

/**
 * The byte code writer utils.
 */
@Internal
public final class ByteCodeWriterUtils {

    private ByteCodeWriterUtils() {
    }

    /**
     * Generate the bytecode.
     *
     * @param objectDef      The object definition
     * @param visitorContext The context
     * @return The generated bytecode
     */
    @NonNull
    public static byte[] writeByteCode(@NonNull ObjectDef objectDef, @Nullable VisitorContext visitorContext) {
        ClassWriter classWriter;
        if (visitorContext != null) {
            classWriter = new ClassWriter(ClassWriter.COMPUTE_MAXS | ClassWriter.COMPUTE_FRAMES) {

                @Override
                protected String getCommonSuperClass(String type1, String type2) {
                    ClassLoader classLoader = getClassLoader();
                    Class<?> class1;
                    try {
                        class1 = Class.forName(type1.replace('/', '.'), false, classLoader);
                    } catch (ClassNotFoundException e) {
                        return getCommonSuperClassUsingVisitorContext(type1, type2);
                    }
                    Class<?> class2;
                    try {
                        class2 = Class.forName(type2.replace('/', '.'), false, classLoader);
                    } catch (ClassNotFoundException e) {
                        return getCommonSuperClassUsingVisitorContext(type1, type2);
                    }
                    if (class1.isAssignableFrom(class2)) {
                        return type1;
                    }
                    if (class2.isAssignableFrom(class1)) {
                        return type2;
                    }
                    if (class1.isInterface() || class2.isInterface()) {
                        return "java/lang/Object";
                    } else {
                        do {
                            class1 = class1.getSuperclass();
                        } while (!class1.isAssignableFrom(class2));
                        return class1.getName().replace('.', '/');
                    }
                }

                private String getCommonSuperClassUsingVisitorContext(String type1, String type2) {
                    ClassElement class1 = getClassElement(type1);
                    ClassElement class2 = getClassElement(type2);
                    if (class2.isAssignable(class1)) {
                        return type1;
                    }
                    if (class1.isAssignable(class2)) {
                        return type2;
                    }
                    if (class1.isInterface() || class2.isInterface()) {
                        return "java/lang/Object";
                    } else {
                        do {
                            class1 = class1.getSuperType().orElse(null);
                        } while (class1 != null && class1.isAssignable(class2));
                        if (class1 == null) {
                            return "java/lang/Object";
                        }
                        return class1.getName().replace('.', '/');
                    }
                }

                private ClassElement getClassElement(String type) {
                    return visitorContext.getClassElement(type.replace('/', '.'))
                        .orElseThrow(() -> new TypeNotPresentException("Type " + type + " not found", null));
                }
            };
        } else {
            classWriter = new ClassWriter(ClassWriter.COMPUTE_MAXS | ClassWriter.COMPUTE_FRAMES);
        }
        new ByteCodeWriter().writeObject(classWriter, objectDef, null);
        return classWriter.toByteArray();
    }

}
